<template>
  <!-- 操作按钮 -->
  <el-button type="primary" style="margin-bottom: 10px" @click="addBanner">+新增轮播图</el-button>

  <!-- 表格展示 -->
  <el-table v-loading="loading" :data="bannerList" style="width: 100%">
    <el-table-column type="index" label="序号" width="100" />
    <el-table-column label="图片">
      <template #default="scope">
        <img :src="scope.row.imgUrl" alt="图片" style="width: 208px; height: 100px" />
      </template>
    </el-table-column>
    <el-table-column prop="distributionSite" label="分发站点" />

    <!-- 操作列 -->
    <el-table-column label="操作" width="200">
      <template #default="{ row }">
        <!-- 编辑按钮 -->
        <el-button type="primary" @click="editBanner(row)">
          <el-icon>
            <Edit />
          </el-icon>
        </el-button>

        <!-- 删除确认框 -->
        <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消" @confirm="deleBanner(row.id)">
          <template #reference>
            <el-button type="danger">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>

    <!-- 无数据提示 -->
    <template #empty>
      <el-empty description="没有数据"></el-empty>
    </template>
  </el-table>

  <!-- 轮播图编辑对话框 -->
  <BannerEdit ref="dialog" @success="onSuccess" />
</template>

<script setup>
// 导入依赖
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import BannerEdit from "./components/BannerEdit.vue";
import { getBannerAPI, deleBannerAPI } from "@/apis/banner.js";

// 响应式数据定义
const bannerList = ref([]);
const loading = ref(false);
const dialog = ref(null);

// 方法定义
// 获取轮播图列表
const getBanner = async () => {
  loading.value = true;
  const res = await getBannerAPI();
  bannerList.value = res.data;
  loading.value = false;
};

// 新增轮播图（打开编辑对话框并传入空对象）
const addBanner = () => {
  dialog.value.open({});
};

// 编辑轮播图（打开编辑对话框并传入当前行数据）
const editBanner = (row) => {
  dialog.value.open(row);
};

// 删除轮播图
const deleBanner = async (id) => {
  const res = await deleBannerAPI(id);
  if (res.code === 1) {
    ElMessage.success("删除成功");
    getBanner();
  }
};

// 编辑对话框成功回调
const onSuccess = () => {
  getBanner();
};

// 生命周期钩子
onMounted(() => {
  getBanner();
});
</script>